<template>
  <div class="flex_cm container" style="height: 100%">
    <search
      :form_data="header_list"
      @changeIsShow="
        (e) => {
          header_list[e].isShow = !header_list[e].isShow;
          header_list[e].value = header_list[e].type == 'input_number' ? ['', ''] : '';
        }
      "
      @search="search_key"
      @reset="
        header_list.forEach((item) => {
          item.value = '';
        }),
          search_key()
      "
    ></search>
    <div class="p_0_10 bg_fff flex1">
      <div class="flex_js p_10_0">
        <div class="flex">
          <div
            class="p_0_10 cp"
            :style="{
              color: top_index == 1 ? '#3580eb' : '',
            }"
            @click="change_top_index(1)"
          >
            今日任务汇报
          </div>
          <span>|</span>
          <div
            class="p_0_10 cp"
            :style="{
              color: top_index == 2 ? '#3580eb' : '',
            }"
            @click="change_top_index(2)"
          >
            我的任务总览
          </div>
        </div>
        <div class="flex">
          <setTable
            :data="header_list"
            :height_size="height_size"
            @changeShowTable="
              (e) => {
                header_list[e].showTable = !header_list[e].showTable;
              }
            "
            @resetTableSet="
              () => {
                header_list.forEach((item) => {
                  item.showTable = true;
                });
              }
            "
            @changeHeightSize="
              (e) => {
                height_size = e;
              }
            "
          ></setTable>
        </div>
      </div>
      <el-table
        style="text-align: center"
        :data="list"
        :max-height="top_index == 1 ? '300' : max_height"
        border
        v-loading="loading"
        :row-style="{
          height: height_size == 1 ? '58px' : height_size == 2 ? '48px' : '38px',
        }"
        :cell-style="{
          padding: height_size == 3 ? '0' : '',
        }"
      >
        <el-table-column
          label="项目名称"
          prop="projectName"
          key="项目名称"
          sortable
          v-if="header_list[0].showTable"
        ></el-table-column>
        <el-table-column
          width="100px"
          label="任务名称"
          prop="taskName"
          key="任务名称"
          sortable
          v-if="header_list[1].showTable"
        ></el-table-column>
        <el-table-column
          width="100px"
          label="任务编码"
          prop="taskCode"
          key="任务编码"
          sortable
          v-if="header_list[2].showTable"
        ></el-table-column>
        <el-table-column
          width="100px"
          label="任务权重"
          prop="taskWeight"
          key="任务权重"
          sortable
          v-if="header_list[3].showTable"
        ></el-table-column>
        <el-table-column
          width="100px"
          label="分配权重"
          prop="assignWeight"
          key="分配权重"
          sortable
          v-if="header_list[4].showTable"
        ></el-table-column>

        <el-table-column
          width="100px"
          label="子任务"
          prop="taskNodeName"
          key="子任务"
          sortable
          v-if="header_list[5].showTable"
        ></el-table-column>
        <el-table-column
          label="状态"
          key="状态"
          sortable
          prop="isDelete"
          width="120px"
          v-if="header_list[6].showTable"
        >
          <template #default="scope">
            <div v-if="scope.row.status == 1">
              未开始 <span v-if="scope.row.isCancel">(已取消)</span>
            </div>
            <div v-if="scope.row.status == 2">
              进行中<span v-if="scope.row.isCancel">(已取消)</span>
            </div>
            <div v-if="scope.row.status == 3">
              延期<span v-if="scope.row.isCancel">(已取消)</span>
            </div>
            <div v-if="scope.row.status == 4">
              已完成<span v-if="scope.row.isCancel">(已取消)</span>
            </div>
            <div v-if="scope.row.status == 5">超时完成</div>
          </template></el-table-column
        >
        <el-table-column
          width="100px"
          label="今日工时"
          prop="usedHours"
          key="今日工时"
          sortable
          v-if="header_list[7].showTable"
        >
          <template #default="scope">
            <el-input
              type="number"
              :disabled="
                ![1, 2, 3].includes(scope.row.status) || top_index == 2 || btn_loading
              "
              v-model="scope.row.todayWorkHours"
              @focus="
                (current_hours = scope.row.todayWorkHours),
                  (today_rate =
                    scope.row.todayCompletionRate == null
                      ? 0
                      : scope.row.todayCompletionRate);
              "
              @blur="change_today_hours({ item: scope.row, type: 1 })"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          width="120px"
          label="今日进度(%)"
          prop="usedHours"
          key="今日进度"
          sortable
          v-if="header_list[8].showTable"
        >
          <template #default="scope">
            <el-input
              type="number"
              :disabled="
                ![1, 2, 3].includes(scope.row.status) || top_index == 2 || btn_loading
              "
              v-model="scope.row.todayCompletionRate"
              @focus="
                (current_hours = scope.row.todayWorkHours),
                  (residue_rate =
                    scope.row.completionRate -
                    (scope.row.todayCompletionRate == null
                      ? 0
                      : scope.row.todayCompletionRate)),
                  (today_rate =
                    scope.row.todayCompletionRate == null
                      ? 0
                      : scope.row.todayCompletionRate);
              "
              @blur="
                change_today_hours({
                  item: scope.row,
                  type: 1,
                })
              "
            ></el-input> </template
        ></el-table-column>
        <el-table-column
          width="100px"
          label="已用工时"
          prop="usedHours"
          key="已用工时"
          sortable
          v-if="header_list[9].showTable"
        ></el-table-column>
        <el-table-column
          width="100px"
          label="总进度(%)"
          prop="completionRate"
          key="总进度"
          sortable
          v-if="header_list[10].showTable"
        ></el-table-column>
        <el-table-column
          width="120"
          label="实际开始时间"
          prop="actualStartTime"
          key="实际开始时间"
          sortable
          v-if="header_list[11].showTable"
          ><template #default="scope">
            <div v-if="scope.row.actualStartTime ?? '' !== ''">
              {{ formatDate(parseInt(scope.row.actualStartTime), "YYYY-MM-DD") }}
            </div>
            <div v-else>-- --</div>
          </template></el-table-column
        >
        <el-table-column
          width="120"
          label="实际完成时间"
          prop="actualFinishTime"
          key="实际完成时间"
          sortable
          v-if="header_list[12].showTable"
          ><template #default="scope">
            <div v-if="scope.row.actualFinishTime ?? '' !== ''">
              {{ formatDate(parseInt(scope.row.actualFinishTime), "YYYY-MM-DD") }}
            </div>
            <div v-else>-- --</div>
          </template></el-table-column
        >
        <el-table-column label="操作" width="120">
          <template #default="scope: any">
            <el-button
              @click="
                router.push({
                  name: 'workHours',
                  query: {
                    pro_name: scope.row.projectName,
                    task_name: scope.row.taskName,
                    node_name: scope.row.taskNodeName,
                  },
                }),
                  EventBus.emit('change_default_active', '/workHours')
              "
              v-if="[2, 3, 4, 5].includes(scope.row.status)"
              >操作记录</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div v-if="top_index == 1">
        <el-divider style="margin: 10px 0"></el-divider>
        <div class="flex_js">
          <div>今日额外工时</div>
          <el-button type="primary" @click="show_box = true">新增今日额外工时</el-button>
        </div>
        <el-table :data="additional_list" border class="tc m_top10" max-height="300">
          <el-table-column
            label="项目名称"
            prop="projectName"
            key="项目名称"
            sortable
          ></el-table-column>
          <el-table-column
            label="任务名称"
            prop="taskName"
            key="任务名称"
            sortable
          ></el-table-column>
          <el-table-column
            label="工时"
            prop="workHours"
            key="工时"
            sortable
          ></el-table-column>
          <el-table-column
            label="备注"
            prop="remark"
            key="备注"
            sortable
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button @click="edit_list(scope.row)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        v-if="top_index == 2"
        class="m_10_0 pagination"
        v-model:currentPage="page_data.current"
        v-model:page-size="page_data.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="list_debounce()"
        @current-change="list_debounce()"
      />
    </div>
    <el-drawer
      v-model="show_box"
      direction="rtl"
      size="30%"
      destroy-on-close
      @close="resetForm(addWordHours)"
      :close-on-click-modal="false"
    >
      <template #title
        ><h4 v-if="add_form_data.id == ''">新增额外工时</h4>
        <h4 v-else>编辑额外工时</h4></template
      >
      <template #default>
        <el-form
          :model="add_form_data"
          :rules="rules"
          ref="addWordHours"
          label-width="100"
        >
          <el-form-item label="项目名称">
            <el-select v-model="add_form_data.taskId">
              <el-option
                v-for="item in project_list"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="任务名称" prop="taskName">
            <el-input v-model="add_form_data.taskName" placeholder="请输入"> </el-input>
          </el-form-item>
          <el-form-item label="额外工时" prop="workHours">
            <el-input-number
              :min="0"
              v-model="add_form_data.workHours"
              type="number"
              placeholder="请输入"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              v-model="add_form_data.remark"
              placeholder="请输入"
              type="textarea"
            ></el-input
          ></el-form-item>
          <div class="tr">
            <el-button @click="resetForm(addWordHours)">取消</el-button>
            <el-button
              type="primary"
              @click="submit_add_hours(addWordHours)"
              :loading="btn_loading"
              >确定</el-button
            >
          </div>
        </el-form>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { check_role, formatDate, debounce, handle_search_key } from "@/utils/check_role"; // 权限校验
import search from "@/view/components/search.vue";
import setTable from "@/view/components/setTable.vue";
import { onMounted, ref, onUnmounted, computed } from "vue";
import axios from "@/service/HttpRequest";
import serviceApi from "@/service/api";
import EventBus from "@/utils/EventBus";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
const store = useStore();
const router = useRouter();
const addWordHours = ref<FormInstance>();
const rules = ref({
  // 表单验证规则
  taskName: [{ required: true, message: "请输入任务名称", trigger: "blur" }],
  workHours: [{ required: true, message: "请输入额外工时", trigger: "blur" }],
});
const list = ref();
const total = ref();
const max_height = ref();
const loading = ref(false);
const show_box = ref(false);
const height_size = ref(1);
const top_index = ref(1);

const header_list = ref<any>([
  {
    label: "项目名称",
    value: "",
    showTable: true,
    type: "input",
    isShow: true,
    options: [],
  },
  {
    label: "任务名称",
    value: "",
    showTable: true,
    type: "input",
    isShow: true,
    options: [],
  },
  {
    label: "任务编码",
    value: "",
    showTable: true,
    type: "input",
    isShow: false,
    options: [],
  },
  {
    label: "任务权重",
    value: "",
    showTable: true,
    type: "input",
    isShow: false,
    options: [],
  },
  {
    label: "分配权重",
    value: "",
    showTable: true,
    type: "input",
    isShow: false,
    options: [],
  },
  {
    label: "子任务",
    value: "",
    showTable: true,
    type: "input",
    isShow: false,
    options: [],
  },
  {
    label: "状态",
    value: "",
    showTable: true,
    type: "select",
    isShow: false,
    options: computed(() => {
      return top_index.value == 1
        ? [
            {
              value: "1",
              label: "未开始",
            },
            {
              value: "2",
              label: "进行中",
            },
            {
              value: "3",
              label: "延期",
            },
          ]
        : [
            {
              value: "1",
              label: "未开始",
            },
            {
              value: "2",
              label: "进行中",
            },
            {
              value: "3",
              label: "延期",
            },
            {
              value: "4",
              label: "已完成",
            },
            {
              value: "5",
              label: "超时完成",
            },
          ];
    }),
  },
  {
    label: "今日工时",
    value: "",
    showTable: true,
    type: "input",
    isShow: false,
    options: [],
  },
  {
    label: "今日进度",
    value: "",
    showTable: true,
    type: "input",
    isShow: false,
    options: [],
  },
  {
    label: "已用工时",
    value: "",
    showTable: true,
    type: "input",
    isShow: false,
    options: [],
  },
  {
    label: "总进度",
    value: "",
    showTable: true,
    type: "input",
    isShow: false,
    options: [],
  },
  {
    label: "实际开始时间",
    value: "",
    showTable: true,
    type: "date",
    isShow: false,
    options: [],
  },
  {
    label: "实际完成时间",
    value: "",
    showTable: true,
    type: "date",
    isShow: false,
    options: [],
  },
]);
const page_data = ref({
  current: 1,
  pageSize: 10,
  enterpriseId: store.state.enterprise_id,
  projectName: "",
  taskName: "",
  taskCode: "",
  taskWeight: "",
  assignWeight: "",
  taskNodeName: "",

  status: "",
  todayWorkHours: "",
  todayCompletionRate: "",
  completionRate: "",
  usedHours: "",
  actualFinishTime: "",
  actualStartTime: "",
});
const residue_rate = ref(); // 剩余进度
const today_rate = ref(); // 今日进度
const current_hours = ref();
const change_today_hours = (e) => {
  console.log(residue_rate.value, today_rate.value, current_hours.value);
  if ((e.item.todayWorkHours ?? "") == "" || (e.item.todayCompletionRate ?? "") == "") {
    return;
  }

  if (
    e.item.todayCompletionRate < 1 ||
    e.item.todayCompletionRate > 100 ||
    e.item.todayWorkHours < 1 ||
    e.item.todayWorkHours > 100
  ) {
    ElMessage.error("如填写工时、进度，需在 1 ~ 100 之间");
    e.item.todayCompletionRate = "";
    e.item.todayWorkHours = "";
    return;
  }
  if (e.item.todayCompletionRate < residue_rate.value) {
    ElMessage.error("今日进度不得少于昨日进度");
    e.item.todayCompletionRate = "";
    return;
  }
  if (
    e.item.todayWorkHours != current_hours.value ||
    e.item.todayCompletionRate != today_rate.value
  ) {
    add_form_data.value.taskId = e.item.taskId;
    add_form_data.value.taskMemberNodeId = e.item.id;
    add_form_data.value.workHours =
      e.item.todayWorkHours == "" || e.item.todayWorkHours === null
        ? 0
        : e.item.todayWorkHours;
    add_form_data.value.completionRate =
      e.item.todayCompletionRate == "" || e.item.todayCompletionRate === null
        ? 0
        : e.item.todayCompletionRate;
    console.log(add_form_data.value);
    btn_loading.value = true;
    add_form_data.value.taskRecordDealType = 2;
    add_form_data.value.taskRecordType = 1;
    submit_workHours_requrest();
  }
};
onMounted(() => {
  max_height.value = window.innerHeight - 320; // 带分页的 table 高度
  EventBus.on("refresh", () => {
    get_list();
    ElMessage.success("刷新成功！");
  });
  setTimeout(() => {
    get_list();
    get_additional_list();
    get_myProjectTaskList();
  }, 100);
});
onUnmounted(() => {
  EventBus.off("refresh");
});
const project_list = ref([]);
const get_myProjectTaskList = () => {
  axios
    .request({ url: serviceApi.myProjectTaskList, method: "post" })
    .then((res) => {
      console.log(res);
      project_list.value = res.data.reverse();
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
const submit_add_hours = async (formEl: FormInstance | undefined) => {
  await formEl.validate((valid) => {
    if (valid) {
      if (btn_loading.value) return;
      btn_loading.value = true;
      add_form_data.value.taskRecordDealType = 2;
      add_form_data.value.taskRecordType = 2;
      axios
        .request({
          url:
            add_form_data.value.id == ""
              ? serviceApi.recordMemberTask
              : serviceApi.editExtraWorkHour,
          method: "post",
          data: add_form_data.value,
        })
        .then((res) => {
          console.log(res);
          ElMessage.success("操作成功！");
          setTimeout(() => {
            btn_loading.value = false;
            show_box.value = false;
            get_additional_list();
          }, 2000);
        })
        .catch((err) => {
          btn_loading.value = false;
          ElMessage.error(err);
        });
    }
  });
};
const btn_loading = ref(false);
const add_form_data = ref<any>({
  id: "",
  taskId: "",
  taskName: "",
  taskMemberNodeId: "",
  taskRecordDealType: "",
  taskRecordType: "",
  remark: "",
  workHours: "",
  completionRate: "",
});
const edit_list = (e) => {
  console.log(e);
  add_form_data.value = {
    id: e.id,
    taskId: e.taskId,
    taskName: e.taskName,
    taskMemberNodeId: "",
    taskRecordDealType: 2,
    taskRecordType: 2,
    remark: e.remark,
    workHours: e.workHours,
    completionRate: "",
  };
  show_box.value = true;
};
const submit_workHours_requrest = () => {
  axios
    .request({
      url: serviceApi.recordMemberTask,
      method: "post",
      data: add_form_data.value,
    })
    .then((res) => {
      console.log(res);
      ElMessage.success("操作成功！");
      show_box.value = false;
      add_form_data.value = {
        id: "",
        taskId: "",
        taskMemberNodeId: "",
        taskRecordDealType: "",
        taskRecordType: "",
        remark: "",
        workHours: "",
      };
      btn_loading.value = false;
      setTimeout(() => {
        get_list();
      }, 1000);
    })
    .catch((err) => {
      btn_loading.value = false;
      ElMessage.error(err);
    });
};
const change_top_index = (e) => {
  header_list.value.forEach((item) => {
    item.value = "";
  });
  top_index.value = e;
  page_data.value.current = 1;
  search_key();
  e == 1 ? get_additional_list() : "";
};
const additional_page_data = ref({
  current: 1,
  pageSize: 1000,
  taskRecordType: 2,
  recordTime: "",
});
const additional_list = ref([]);
const get_additional_list = () => {
  let data = handle_search_key(additional_page_data.value) as any;
  data.recordTime.detailList[0].value = Date.parse(
    new Date(new Date().toLocaleDateString()) + ""
  );
  axios
    .request({
      url: serviceApi.myWorkHours,
      method: "post",
      data: data,
    })
    .then((res) => {
      console.log(res);
      additional_list.value = res.data.content;
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
const get_list = () => {
  loading.value = true;
  let data = handle_search_key(page_data.value) as any;
  if (top_index.value == 1) {
    data.status.type = data.status.detailList[0].value == "" ? "LESS_THAN" : "INNER_LIKE";
    data.status.detailList[0].value =
      data.status.detailList[0].value == "" ? 4 : data.status.detailList[0].value;
    data.pageSize = 1000;
  } else {
    data.status.type = "INNER_LIKE";
  }
  console.log(data);
  axios
    .request({
      url: serviceApi.myTaskPage,
      method: "post",
      data: data,
    })
    .then((res) => {
      console.log(res.data);
      list.value =
        top_index.value == 1
          ? res.data.content.filter((i) => {
              return !i.isCancel;
            })
          : res.data.content;
      total.value = parseInt(res.data.totalElements);
      loading.value = false;
    })
    .catch((err) => {
      ElMessage.error(err);
      loading.value = false;
    });
};
let list_debounce = debounce(200, get_list);
const search_key = () => {
  page_data.value = {
    current: 1,
    pageSize: 10,
    enterpriseId: store.state.enterprise_id,
    projectName: header_list.value[0].value,
    taskName: header_list.value[1].value,
    taskCode: header_list.value[2].value,
    taskWeight: header_list.value[3].value,
    assignWeight: header_list.value[4].value,
    taskNodeName: header_list.value[5].value,
    status: header_list.value[6].value,
    todayWorkHours: header_list.value[7].value,
    todayCompletionRate: header_list.value[8].value,
    usedHours: header_list.value[9].value,
    completionRate: header_list.value[10].value,
    actualStartTime: header_list.value[11].value,
    actualFinishTime: header_list.value[12].value,
  };
  get_list();
};
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  add_form_data.value = {
    id: "",
    taskId: "",
    workHours: "",
    taskRecordDealType: 2,
    taskRecordType: 2,
    remark: "",
    taskName: "",
  };
  show_box.value = false;
};
</script>

<style lang="scss" scoped>
.top_item {
  border: 1px solid #ccc;
  cursor: pointer;
  padding: 5px;
  border-radius: 5px;
  display: flex;
  align-items: center;
  &:hover {
    color: #3580eb;
    border-color: #3580eb;
  }
}
.line {
  background-color: #333;
  width: 1px;
  height: 16px;
  margin: 0 10px;
}
</style>
